﻿#include "KSpinboxDeleget.h"

#include <QDoubleSpinBox>
#include <QDebug>

KSpinboxDeleget::KSpinboxDeleget(QObject *parent)
	: QItemDelegate(parent)
{
	//QStyledItemDelegate;

	doublespin_decimals = 2;
}

KSpinboxDeleget::~KSpinboxDeleget()
{
}

QWidget* KSpinboxDeleget::createEditor(QWidget*parent, const QStyleOptionViewItem&option, const QModelIndex&index) const
{
	QVariant v = index.model()->data(index);
	if (v.type() == QVariant::Double) {
		QDoubleSpinBox*editor = new QDoubleSpinBox(parent);
		connect(editor, SIGNAL(editingFinished()), SLOT(commitAndCloseEditor()));
		editor->setFrame(false);
		editor->setDecimals(doublespin_decimals);
		editor->setRange(-DBL_MAX, DBL_MAX);
		return editor;
	}
	return QItemDelegate::createEditor(parent, option, index);
}
void KSpinboxDeleget::setModelData(QWidget*editor, QAbstractItemModel*model, const QModelIndex&index) const
{
	QVariant v = model->data(index);
	if (v.type() == QVariant::Double) {
		QDoubleSpinBox*spin = static_cast<QDoubleSpinBox*>(editor);
		v.setValue(spin->value());
		model->setData(index, v, Qt::EditRole);
		return;
	}
	QItemDelegate::setModelData(editor, model, index);
}

void KSpinboxDeleget::paint(QPainter*painter, const QStyleOptionViewItem&option, const QModelIndex&index) const
{
	//QVariant v = index.model()->data(index);
	//if (v.type() == QVariant::Double) {
	//	QString text = QString("%1").arg(v.toDouble(), 0, 'f', doublespin_decimals, QChar('0'));
	//	//QString::number()
	//	qDebug() << "doublespin:" << doublespin_decimals << "," << text;
	//	QStyleOptionViewItem my = option;
	//	my.displayAlignment = Qt::AlignHCenter | Qt::AlignVCenter;
	//	drawDisplay(painter, my, option.rect, text);
	//	drawFocus(painter, my, option.rect);
	//	return;
	//}

	QItemDelegate::paint(painter, option, index);
}

void KSpinboxDeleget::commitAndCloseEditor()
{
	QDoubleSpinBox*spin = qobject_cast<QDoubleSpinBox*>(sender());
	emit commitData(spin);
	emit closeEditor(spin);
}
